// ZENrs FFI集成示例 - Zig端
// 这个文件展示了如何在exokernel中使用我们实现的FFI功能

const std = @import("std");
const zenrs_ffi = @import("zenrs_ffi");

// 从Rust导入的FFI函数
extern "C" fn zenrs_create_message(
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data_size: u64
) [*c]zenrs_ffi.ZenrsMessage;

extern "C" fn zenrs_free_message(message_ptr: [*c]zenrs_ffi.ZenrsMessage) void;

extern "C" fn zenrs_process_string(input: [*c]const u8) [*c]u8;

extern "C" fn zenrs_free_string(str_ptr: [*c]u8) void;

extern "C" fn zenrs_get_version() [*c]const u8;

extern "C" fn zenrs_fibonacci(n: u32) u64;

extern "C" fn zenrs_fibonacci_iterative(n: u32) u64;

extern "C" fn zenrs_create_config() [*c]zenrs_ffi.ZenrsConfig;

extern "C" fn zenrs_free_config(config_ptr: [*c]zenrs_ffi.ZenrsConfig) void;

extern "C" fn zenrs_update_config(
    config_ptr: [*c]zenrs_ffi.ZenrsConfig,
    debug_level: u32,
    log_to_console: bool,
    max_threads: u32
) c_int;

// 增强型Exokernel管理器
pub const EnhancedExokernelManager = struct {
    // 初始化增强型Exokernel管理器
    pub fn init() EnhancedExokernelManager {
        return EnhancedExokernelManager{};
    }
    
    // 获取Rust版本信息
    pub fn get_rust_version(self: EnhancedExokernelManager) []const u8 {
        _ = self;
        const version = zenrs_get_version();
        return std.mem.sliceTo(version, 0);
    }
    
    // 获取系统信息（调用自身的函数）
    pub fn get_system_info(self: EnhancedExokernelManager, buffer: []u8) !usize {
        _ = self;
        const result = zenrs_ffi.zenrs_zig_get_system_info(
            buffer.ptr,
            buffer.len() as u64
        );
        
        if (result < 0) {
            return error.SystemInfoError;
        }
        
        return @intCast(usize, result);
    }
    
    // 创建并管理消息
    pub fn create_and_manage_message(
        self: EnhancedExokernelManager,
        message_type: u32,
        sender_id: u64,
        target_id: u64,
        data_size: u64
    ) !void {
        _ = self;
        // 创建消息
        const message = zenrs_create_message(message_type, sender_id, target_id, data_size);
        defer zenrs_free_message(message);
        
        if (message == null) {
            return error.MessageCreationFailed;
        }
        
        std.debug.print("Created message: type={}, sender={}, target={}, data_size={}\n",
            .{message.*.message_type, message.*.sender_id, message.*.target_id, message.*.data_size});
        
        // 如果有数据缓冲区，初始化它
        if (message.*.data_ptr != null and data_size > 0) {
            const data_buffer = message.*.data_ptr[0..@intCast(usize, data_size)];
            @memset(data_buffer, 0xCC); // 填充一些测试数据
            std.debug.print("Initialized message data buffer\n", .{});
            
            // 简单验证
            if (data_buffer[0] == 0xCC) {
                std.debug.print("Message data buffer verification successful\n", .{});
            }
        }
    }
    
    // 使用Rust处理字符串
    pub fn process_string_with_rust(self: EnhancedExokernelManager, input: []const u8) ![]const u8 {
        _ = self;
        // 创建一个以null结尾的字符串
        const c_string = try std.heap.page_allocator.allocSentinel(u8, input.len, 0);
        defer std.heap.page_allocator.free(c_string);
        
        @memcpy(c_string, input);
        
        // 调用Rust函数处理字符串
        const processed_ptr = zenrs_process_string(c_string.ptr);
        defer zenrs_free_string(processed_ptr);
        
        if (processed_ptr == null) {
            return error.StringProcessingFailed;
        }
        
        // 转换为Zig字符串
        const processed_str = std.mem.sliceTo(processed_ptr, 0);
        
        // 复制结果，因为原始字符串将在defer中被释放
        const result = try std.heap.page_allocator.dupe(u8, processed_str);
        return result;
    }
    
    // 使用Zig处理字符串
    pub fn process_string_with_zig(self: EnhancedExokernelManager, input: []const u8) ![]const u8 {
        _ = self;
        // 创建一个以null结尾的字符串
        const c_string = try std.heap.page_allocator.allocSentinel(u8, input.len, 0);
        defer std.heap.page_allocator.free(c_string);
        
        @memcpy(c_string, input);
        
        // 调用Zig函数处理字符串
        const processed_ptr = zenrs_ffi.zenrs_zig_process_string(c_string.ptr);
        defer zenrs_ffi.zenrs_zig_free_string(processed_ptr);
        
        if (processed_ptr == null) {
            return error.StringProcessingFailed;
        }
        
        // 转换为Zig字符串
        const processed_str = std.mem.sliceTo(processed_ptr, 0);
        
        // 复制结果
        const result = try std.heap.page_allocator.dupe(u8, processed_str);
        return result;
    }
    
    // 测试斐波那契数列计算
    pub fn test_fibonacci(self: EnhancedExokernelManager, n: u32) void {
        _ = self;
        // 测试递归版本
        const start_time = std.time.nanoTimestamp();
        const fib_result = zenrs_fibonacci(n);
        const end_time = std.time.nanoTimestamp();
        const duration = (end_time - start_time) / 1_000_000;
        
        std.debug.print("Fibonacci({}) = {} (took {}ms)\n", .{n, fib_result, duration});
        
        // 测试迭代版本
        const iter_start_time = std.time.nanoTimestamp();
        const iter_fib_result = zenrs_fibonacci_iterative(n);
        const iter_end_time = std.time.nanoTimestamp();
        const iter_duration = (iter_end_time - iter_start_time) / 1_000_000;
        
        std.debug.print("Iterative Fibonacci({}) = {} (took {}ms)\n", .{n, iter_fib_result, iter_duration});
    }
    
    // 测试配置管理
    pub fn test_config_management(self: EnhancedExokernelManager) !void {
        _ = self;
        // 创建配置
        const config = zenrs_create_config();
        defer zenrs_free_config(config);
        
        if (config == null) {
            return error.ConfigCreationFailed;
        }
        
        // 显示默认配置
        std.debug.print("Default config: debug_level={}, log_to_console={}, max_threads={}\n",
            .{config.*.debug_level, config.*.log_to_console, config.*.max_threads});
        
        // 更新配置
        const update_result = zenrs_update_config(config, 3, false, 16);
        if (update_result != zenrs_ffi.ZENRS_OK) {
            return error.ConfigUpdateFailed;
        }
        
        // 显示更新后的配置
        std.debug.print("Updated config: debug_level={}, log_to_console={}, max_threads={}\n",
            .{config.*.debug_level, config.*.log_to_console, config.*.max_threads});
    }
    
    // 创建和管理Zig对象
    pub fn create_and_manage_zig_object(self: EnhancedExokernelManager, size: u64) !void {
        _ = self;
        // 创建对象
        const object = zenrs_ffi.zenrs_zig_create_object(size);
        defer zenrs_ffi.zenrs_zig_free_object(object, size);
        
        if (object == null) {
            return error.ObjectCreationFailed;
        }
        
        std.debug.print("Created Zig object of size {} bytes at {p}\n", .{size, object});
        
        // 使用对象（例如读取一些数据）
        const data = @ptrCast([*]u8, object)[0..@intCast(usize, size)];
        std.debug.print("Object data first byte: 0x{x}\n", .{data[0]});
        
        // 修改对象数据
        if (size > 0) {
            data[0] = 0xFF;
            std.debug.print("Modified object data first byte to: 0x{x}\n", .{data[0]});
        }
    }
};

// 运行FFI集成测试
pub fn run_ffi_integration_test() !void {
    std.debug.print("\n=== Starting ZENrs FFI Integration Test (Zig Side) ===\n", .{});
    
    // 创建增强型Exokernel管理器
    const manager = EnhancedExokernelManager.init();
    
    // 测试版本信息
    const version = manager.get_rust_version();
    std.debug.print("Rust FFI version: {s}\n", .{version});
    
    // 测试系统信息
    var system_info_buffer: [1024]u8 = undefined;
    const info_size = try manager.get_system_info(&system_info_buffer);
    const system_info = system_info_buffer[0..info_size];
    std.debug.print("System info:\n{s}\n", .{system_info});
    
    // 测试字符串处理（Rust）
    const test_string = "Hello from Zig FFI test!";
    const rust_processed = try manager.process_string_with_rust(test_string);
    defer std.heap.page_allocator.free(rust_processed);
    std.debug.print("Original string: {s}\n", .{test_string});
    std.debug.print("Processed by Rust: {s}\n", .{rust_processed});
    
    // 测试字符串处理（Zig）
    const zig_processed = try manager.process_string_with_zig(test_string);
    defer std.heap.page_allocator.free(zig_processed);
    std.debug.print("Processed by Zig: {s}\n", .{zig_processed});
    
    // 测试消息管理
    try manager.create_and_manage_message(1, 100, 200, 32);
    
    // 测试斐波那契计算
    manager.test_fibonacci(35);
    
    // 测试配置管理
    try manager.test_config_management();
    
    // 测试Zig对象管理
    try manager.create_and_manage_zig_object(128);
    
    std.debug.print("\n=== ZENrs FFI Integration Test (Zig Side) Completed Successfully ===\n", .{});
}

// 在实际应用中，你可以在main.zig中调用这个测试函数
// 例如：
// 
// pub fn main() !void {
//     // ... 初始化代码 ...
//     
//     // 运行FFI集成测试
//     try ffi_example.run_ffi_integration_test();
//     
//     // ... 主循环代码 ...
// }